
; 2.3.2 实例: 符号求导

(define (=number? x num)
  (and (number? x) (= x num)))

(define (variable? x) (symbol? x))

(define (same-variable? v1 v2)
  (and (variable? v1) (variable? v2) (eq? v1 v2)))

(define (sum? x)
  (and (pair? x) (eq? (car x) '+)))

(define (make-sum a1 a2)
  (cond ((=number? a1 0) a2)
        ((=number? a2 0) a1)
        ((and (number? a1) (number? a2)) (+ a1 a2))
        (else (list '+ a1 a2))))

; (+ a b): #t; (+ a b c): #f
(define (binary-expression? e) (null? (cdddr e)))
; (+ a b) -> b
(define (second-term e) (caddr e))
; (+ a b c) -> (b c)
(define (all-but-first-term e) (cddr e))

(define (reduce-expression op e)
 (if (binary-expression? e)
  (second-term e)
  (cons op (all-but-first-term e))))

; e的被加数
(define (addend e) (cadr e))
; e的加数
;(define (augend e) (caddr e))
(define (augend e) (reduce-expression '+ e))

(define (product? x)
  (and (pair? x) (eq? (car x) '*)))

(define (make-product a1 a2)
  (cond ((or (=number? a1 0) (=number? a2 0)) 0)
        ((=number? a1 1) a2)
        ((=number? a2 1) a1)
        ((and (number? a1) (number? a2)) (* a1 a2))
        (else (list '* a1 a2))))

; e的被乘数
(define (multiplier p) (cadr p))
; e的乘数
;(define (multiplicand p) (caddr p))
(define (multiplicand e) (reduce-expression '* e))

(define (exponentiation? e)
 (and (pair? e) (eq? (car e) '**)))

(define (base e) (cadr e))
(define (exponent e) (caddr e))
(define (make-exponentiation a1 a2)
 (cond  ((=number? a2 0) 1)
        ((=number? a1 1) 1)
        ((=number? a1 0) 0)
        ((and (number? a1) (number? a2)) (exp a1 a2)) ; exp or exersise 1.16 fast-expt
        (else (list '** a1 a2))))

; dc/dx = 0
; dx/dx = 1
; d(u+v)/dx = du/dx + dv/dx
; d(uv)/dx = u(dv/dx) + v(du/dx)
; d(u^n)/dx = nu^(n-1)(du/dx)
(define (deriv e var)
  (cond ((number? e) 0)
        ((variable? e)
         (if (same-variable? e var) 1 0))
        ((sum? e)
         (make-sum (deriv (addend e) var)
                   (deriv (augend e) var)))
        ((product? e)
         (make-sum
           (make-product (multiplier e) (deriv (multiplicand e) var))
           (make-product (multiplicand e) (deriv (multiplier e) var))))
        ((exponentiation? e)
         (let ((u (base e))
               (n (exponent e)))
           (make-product
             (make-product n (make-exponentiation u (make-sum n -1))) ; note using make-sum here!
             (deriv u var))))
        (else
         (error "unknown expression type -- DERIV" e))))

(define e '(* x y (+ x u 3)))

(display
 (deriv e 'x))
